package com.supercube.wechat.controller;

import com.supercube.common.config.SuperCubeConfig;
import com.supercube.common.controller.BaseController;
import com.supercube.common.utils.FileUtil;
import com.supercube.common.utils.JavaScriptUtils;
import com.supercube.wechat.domain.SlideImageDO;
import com.supercube.wechat.service.SlideImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

/**
 * 轮播图控制器
 *
 * @author djzhao
 * @date 19/10/20 22:33
 * @email djzhao627@gmail.com
 */
@Controller
@RequestMapping("wechat/home/slideImage")
public class SlideImageController extends BaseController {

    @Autowired
    private SlideImageService slideImageService;

    @Autowired
    private SuperCubeConfig fcConfig;

    @GetMapping("")
    public String list(Model model) {
        model.addAttribute("list", slideImageService.list());
        return "wechat/home/slideImage/index";
    }

    @PostMapping("/add")
    public String add(SlideImageDO slideImageDO, MultipartFile file) {
        if (isFileEmpty(slideImageDO, file)) {
            return JavaScriptUtils.JSAlert("没有上传图片");
        }
        if (slideImageService.save(slideImageDO) > 0) {
            return "redirect:/wechat/home/slideImage";
        }
        return JavaScriptUtils.JSAlert("删除失败");
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public String update(SlideImageDO slideImageDO, MultipartFile file) {
        if (isFileEmpty(slideImageDO, file)) {
            return JavaScriptUtils.JSAlert("没有上传图片");
        }
        if (slideImageService.update(slideImageDO) > 0) {
            return "redirect:/wechat/home/slideImage";
        }
        return JavaScriptUtils.JSAlert("删除失败");
    }

    /**
     * 删除
     */
    @GetMapping("/remove")
    // @RequiresPermissions("common:remove")
    public String remove(int id) {
        if (slideImageService.remove(id) > 0) {
            return "redirect:/wechat/home/slideImage";
        }
        return JavaScriptUtils.JSAlert("删除失败");
    }

    /**
     * 判断是否没有上传文件
     *
     * @param slideImageDO 图片对象
     * @param file         文件
     * @return 是否为空
     */
    private boolean isFileEmpty(SlideImageDO slideImageDO, MultipartFile file) {
        if (file.isEmpty()) {
            return true;
        }
        try {
            String fileName = file.getOriginalFilename();
            String fileId = FileUtil.renameToUUID(fileName);
            slideImageDO.setImgUrl(fileId);
            FileUtil.uploadFile(file.getBytes(), fcConfig.getUploadPath(), fileId);
        } catch (Exception e) {
//            log.error("文件上传出错");
        }
        return false;
    }
}
